package com.netty.pro.netty.nianbao_chaibao;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @author xuzn
 * @ClassName: TcpClientHandler
 * @ProjectName netty-pro
 * @date 2020/3/21/9:49
 */
public class MyTcpClientHandler extends SimpleChannelInboundHandler<SendMessage> {
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, SendMessage msg) throws Exception {
    int len = msg.getLen();
    byte[] content = msg.getContent();
    System.out.println("客户端收到消息如下:");
    System.out.println("长度:" + len);
    System.out.println("内容:" + new String(content, CharsetUtil.UTF_8));
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    // 发送数据 hello,netty
    for (int i = 0; i < 10; i++) {
      String msg = "hello,netty";
      byte[] content = msg.getBytes(CharsetUtil.UTF_8);
      int length = msg.getBytes(CharsetUtil.UTF_8).length;
      SendMessage sendMessage = new SendMessage();
      sendMessage.setContent(content);
      sendMessage.setLen(length);
      ctx.writeAndFlush(sendMessage);
    }
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
  }
}
